package com.example.demo.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.elasticsearch.bootstrap.Elasticsearch;
import org.elasticsearch.index.query.QueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import com.example.demo.dao.MyNewsRepository;
import com.example.demo.dao.NewsRepository;
import com.example.demo.model.News;

@Service
public class TestService {
	
	@Autowired
	ElasticsearchTemplate elasticsearchTemplate;
	
	@Autowired
	private MyNewsRepository myNewsRepository;
	
	@Autowired
	private NewsRepository yNewsRepository;
	
	public void init(){
		elasticsearchTemplate.createIndex(News.class);
        for (int i = 0; i < 100; i++) {
            com.example.demo.model.News news = new News();
            news.setId(i+"");
            news.setTitle(i + "单元测试用例");
            news.setContent("单元测试用例"+i+"xxxxx");
            news.setCreatedDateTime(new Date());
            News result=yNewsRepository.save(news);
            System.out.println(result.toString());
        }
    }
	
	public List<com.example.demo.model.News> search(String title)
	{
		return yNewsRepository.findByTitle(title);
	}
	
	public static <T> List<T> toList(final Iterable<T> iterable) {
	    return StreamSupport.stream(iterable.spliterator(), false)
	                        .collect(Collectors.toList());
	}
	
	public List<News> findAll() {
		return toList(yNewsRepository.findAll());
	}

	public Iterable<News> search(QueryBuilder query) {
		return yNewsRepository.search(query);
	}
	
	public void deleteAll(String id){
		 yNewsRepository.delete(id);
	}
}